package com.ternnetwork.batch.quartz.scheduler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.quartz.CronTrigger;
import org.springframework.batch.core.configuration.JobLocator;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import com.ternnetwork.batch.quartz.trigger.TestUserJobTriggerConfiguration;


/**
 * 调度工厂配置
 * @author xuwenfeng
 *
 */
@Configuration
public class SchedulerFactoryBeanConfiguration {
	
	@Autowired
	private TestUserJobTriggerConfiguration testUserJobTriggerConfiguration;
	
	@Autowired
    @Qualifier(value = "dataSource")
    private DataSource dataSource;
	
	
	@Resource
	private JobLauncher jobLauncher;
	
	@Autowired
	private JobLocator jobLocator;
	

	
	@Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

	
	@Bean
	public SchedulerFactoryBean schedulerFactoryBean() throws IOException{
		
		SchedulerFactoryBean schedulerFactor = new SchedulerFactoryBean();
		
		
		schedulerFactor.setQuartzProperties(quartzProperties());
		
		schedulerFactor.setDataSource(dataSource);
		
		
		Map<String,Object> schedulerContextAsMap=new HashMap<String,Object>(5);
		
		schedulerContextAsMap.put("jobLauncher",jobLauncher);
		
		schedulerContextAsMap.put("jobLocator",jobLocator);
		
		schedulerFactor.setSchedulerContextAsMap(schedulerContextAsMap);
		
		CronTrigger testUserJobTrigger=testUserJobTriggerConfiguration.cronTriggerFactoryBean().getObject();
		
		//多个触发器用逗号分隔
		schedulerFactor.setTriggers(testUserJobTrigger);
		
		return schedulerFactor;
	}

}
